package com.cake.liulanxiangzhu.service.impl;

import com.cake.liulanxiangzhu.exception.ServiceException;
import com.cake.liulanxiangzhu.mapper.*;
import com.cake.liulanxiangzhu.pojo.dto.CartDTO;
import com.cake.liulanxiangzhu.pojo.dto.OmsOrderSearchDTO;
import com.cake.liulanxiangzhu.pojo.entity.*;
import com.cake.liulanxiangzhu.pojo.vo.*;
import com.cake.liulanxiangzhu.service.OmsOrderService;
import com.cake.liulanxiangzhu.utils.DataUseUtil;
import com.cake.liulanxiangzhu.utils.LoginUtil;
import com.cake.liulanxiangzhu.web.CakeStateCode;
import com.cake.liulanxiangzhu.web.JsonPage;
import com.cake.liulanxiangzhu.web.ServiceCode;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 订单信息表(OmsOrder)表服务实现类
 *
 * @author dinghao
 * @since 2023-02-23 14:54:20
 */
@Service
@Transactional
public class OmsOrderServiceImpl implements OmsOrderService {
    @Autowired
    private OmsOrderMapper omsOrderMapper;

    @Autowired
    private ContactInformationMapper contactInformationMapper;

    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;

    @Autowired
    private UserShopMapper userShopMapper;

    @Autowired
    private AdminCakeskuMapper adminCakeskuMapper;

    @Autowired
    private OmsCartMapper omsCartMapper;
    @Autowired
    private LoginUtil loginUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public OmsOrderVO queryById(String orderId) {
        return this.omsOrderMapper.queryById(orderId);
    }

    /**
     * 分页查询
     *
     * @param request
     * @param omsOrder 筛选条件
     * @return 查询结果
     */
    @Override
    public JsonPage<OmsOrderVO> queryByPage(HttpServletRequest request, OmsOrder omsOrder, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        String token = request.getHeader("Token");
        if (DataUseUtil.isBlank(token)) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "用户未登录");
        }
        String userId = loginUtil.parser(token).getId();
        omsOrder.setUserId(Integer.parseInt(userId));
        if (omsOrder.getState()!=null && omsOrder.getState()==0){
            omsOrder.setState(null);
        }
        List<OmsOrderVO> omsOrderVOS = omsOrderMapper.queryAllByUserId(omsOrder);
        for (OmsOrderVO omsOrderVO : omsOrderVOS) {
            Integer state = omsOrderVO.getState();
            if (DataUseUtil.isNotBlank(String.valueOf(state))) {
                omsOrderVO.setStateNm(CakeStateCode.getDesc(state));
            } else {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "该订单没有订单状态");
            }
        }

        return JsonPage.restPage(new PageInfo<>(omsOrderVOS));
    }

    /**
     * 点击立即结算
     *
     * @param request
     * @param cartDTO
     * @return 实例对象
     */
    @Override
    public Pay insert(HttpServletRequest request, CartDTO cartDTO) {
        List<OmsOrderItem> entities = cartDTO.getEntities();
        String token = request.getHeader("Authorization");
        if (DataUseUtil.isBlank(token)) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "用户未登录");
        }
        String userId = String.valueOf(loginUtil.parser(token).get("id", Integer.class));
        Pay pay = priceCount(entities, userId);
        return pay;
    }

    /**
     * 计算金额的方法
     *
     * @param userId
     * @param entities
     * @return 实例对象
     */
    public Pay priceCount(List<OmsOrderItem> entities, String userId) {
        Pay pay = new Pay();
        BigDecimal price = new BigDecimal(0);//支付金额
        BigDecimal freight = new BigDecimal(0);//运费
        BigDecimal discount = new BigDecimal(0);//优惠金额
        BigDecimal count = null;
        //获得需要支付的总金额
        for (OmsOrderItem entity : entities) {
            AdminCakesku adminCakesku = adminCakeskuMapper.selectById(entity.getSkuId());
            price = price.add(adminCakesku.getCakePrice().multiply(new BigDecimal(entity.getQuantity())));//根据购买内容获得商品原价
        }
        //根据总金额设置运费
        if (price.compareTo(new BigDecimal(100)) >= 0) {
            freight = new BigDecimal(30);
        }
        //计算优惠金额
        UserShopVO userVo = userShopMapper.queryDiscont(Integer.parseInt(userId));
        if (userVo.getDiscount() != null) {
            count = new BigDecimal(String.valueOf(userVo.getDiscount()));//获得折扣信息
        } else {
            count = new BigDecimal(String.valueOf(0));
        }
        discount = price.subtract(price.multiply(count));
        //实际支付金额
        pay.setActualPay(price.add(freight).subtract(discount)); //实际支付
        pay.setPrice(price);
        pay.setDiscount(discount);
        pay.setFreight(freight);
        return pay;
    }

    @Override
    public void insertBatch(List<OmsOrder> entities) {
        for (OmsOrder entity : entities) {
            entity.setCreatTime(new Date());
            entity.setUpdateTime(new Date());
        }
        omsOrderMapper.insertBatch(entities);
    }

    @Override
    public Integer insertCartBatch(HttpServletRequest request, CartDTO cartDTO) throws ParseException {
        List<OmsOrderItem> entities = cartDTO.getEntities();
        String gmtAppointment = cartDTO.getGmtAppointment();
        Integer id = cartDTO.getId();
        String token = request.getHeader("Token");
        if (DataUseUtil.isBlank(token)) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "用户未登录");
        }
        String userId = loginUtil.parser(token).getId();
        ContactInformationVO contactInformationVO = contactInformationMapper.queryById(id);
        for (OmsOrderItem item : entities) {
            AdminCakesku adminCakesku = adminCakeskuMapper.selectById(item.getSkuId());
            Integer quantity = item.getQuantity();
            /**
             * 设置订单信息数据
             * **/
            OmsOrder omsOrder = new OmsOrder();
            BigDecimal count = null;
            String sn = UUID.randomUUID().toString();
            omsOrder.setSn(sn);
            omsOrder.setUserId(Integer.parseInt(userId));
            omsOrder.setUserName(contactInformationVO.getName());
            omsOrder.setUserTelephone(String.valueOf(contactInformationVO.getTelephone()));
            omsOrder.setShopAddress(contactInformationVO.getAddress());
            omsOrder.setState(CakeStateCode.UNPAY.getCode());
            omsOrder.setGmtPay(new Date());


            Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(gmtAppointment.trim());
            omsOrder.setGmtAppointment(parse);

            BigDecimal originalPrice = adminCakesku.getCakePrice().multiply(BigDecimal.valueOf(quantity));//获得原价
            omsOrder.setOriginalPrice(originalPrice);//设置原价
            UserShopVO userShopVO = userShopMapper.queryDiscont(Integer.parseInt(userId));
            if (userShopVO.getDiscount() != null) {
                count = new BigDecimal(String.valueOf(userShopVO.getDiscount()));//获得折扣信息
            } else {
                count = new BigDecimal(String.valueOf(0));
            }
            omsOrder.setFreight(new BigDecimal(String.valueOf(0)));//设置运费
            BigDecimal freight = omsOrder.getFreight();
            BigDecimal discount = originalPrice.subtract(originalPrice.multiply(count));//获得优惠金额
            omsOrder.setDiscount(discount);//设置优惠金额
            BigDecimal actualPay = originalPrice.add(freight).subtract(discount);//获得实际支付金额
            omsOrder.setActualPay(actualPay);//设置实际支付金额
            omsOrder.setDelivery(0);
            omsOrder.setGmtOrder(new Date());
            omsOrder.setCreatTime(new Date());
            omsOrder.setUpdateTime(new Date());
            omsOrderMapper.insert(omsOrder);

            /**
             * 设置订单商品信息数据
             * **/
            OmsOrderItem orderItem = new OmsOrderItem();
            BeanUtils.copyProperties(adminCakesku, orderItem);
            String skuName = adminCakesku.getSkuName();
            orderItem.setTitle(skuName);
            orderItem.setQuantity(item.getQuantity());
            orderItem.setOrderId(omsOrder.getOrderId());
            orderItem.setCreatTime(new Date());
            orderItem.setUpdateTime(new Date());
            /**
             * 减少库存
             * **/
            Integer cakeStock = adminCakeskuMapper.selectById(item.getSkuId()).getCakeStock();
            Integer quantitySku = cakeStock - item.getQuantity();
            AdminCakesku cakeSku = new AdminCakesku();
            if (quantitySku < 0) {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "库存不足,无法下单");
            } else {
                cakeSku.setSkuId(item.getSkuId());
                cakeSku.setCakeStock(quantitySku);
                adminCakeskuMapper.updateById(cakeSku);
            }
            /**
             * 删除购物车信息
             * **/

            OmsCartVO omsCartVO = omsCartMapper.queryByUserIdSkuId(Integer.parseInt(userId), item.getSkuId());
            if (omsCartVO != null) {
                omsCartMapper.deleteByUserIdSkuId(Integer.parseInt(userId), item.getSkuId());
            }
            //新增订单商品
            omsOrderItemMapper.insert(orderItem);

            /**
             * 支付后修改账户余额
             * **/
            UserShopVO userVo = userShopMapper.queryById(Integer.parseInt(userId));
            BigDecimal balance = userVo.getBalance();//获取当前用户余额
            BigDecimal afBalance = balance.subtract(actualPay);
            if (afBalance.compareTo(BigDecimal.ZERO) >= 0) {
                UserShop userShop = new UserShop();
                userShop.setUserId(Integer.parseInt(userId));
                userShop.setBalance(afBalance);
                userShop.setUpdateTime(new Date());
                userShopMapper.update(userShop);
                /**
                 * 支付后修改支付状态
                 * **/
                OmsOrder upOmsOrder = new OmsOrder();
                upOmsOrder.setSn(sn);
                upOmsOrder.setState(CakeStateCode.PAY.getCode());
                upOmsOrder.setGmtPay(new Date());
                omsOrderMapper.updateBySn(upOmsOrder);
            } else {
                return 400;
            }
        }
        return 0;

    }


    /**
     * 立即支付
     *
     * @param id
     * @param gmtAppointment
     * @param orderId
     * @return 实例对象
     */
    @Override
    public void update(Integer id, String gmtAppointment, Integer orderId) {
        ContactInformationVO contactInformationVO = contactInformationMapper.queryById(id);
        Integer userId = contactInformationVO.getUserId();
        String name = contactInformationVO.getName();
        String telephone = contactInformationVO.getTelephone();
        String address = contactInformationVO.getAddress();
        /**
         * 修改订单支付状态和支付时间
         * **/
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setOrderId(orderId);
        omsOrder.setUserName(name);
        omsOrder.setUserTelephone(telephone);
        omsOrder.setShopAddress(address);
        omsOrder.setState(CakeStateCode.PAY.getCode());
        omsOrder.setGmtPay(new Date());
        try {
            Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(gmtAppointment);
            omsOrder.setGmtAppointment(parse);
        } catch (ParseException e) {
            //LOGGER.error("时间转换错误, string = {}", s, e);
        }
        omsOrder.setUpdateTime(new Date());
        omsOrderMapper.update(omsOrder);
        /**
         * 支付后修改账户余额
         * **/
        UserShopVO userShopVO = userShopMapper.queryById(userId);
        BigDecimal balance = userShopVO.getBalance();//获取当前用户余额
        OmsOrderVO orderVO = omsOrderMapper.queryOrderById(orderId);
        BigDecimal actualPay = orderVO.getActualPay();//获取支付金额
        BigDecimal afBalance = balance.subtract(actualPay);
        UserShop userShop = new UserShop();
        userShop.setUserId(userId);
        userShop.setBalance(afBalance);
        userShop.setUpdateTime(new Date());
        userShopMapper.update(userShop);
    }

    /**
     * 通过主键删除数据
     *
     * @param orderId 主键
     * @return 是否成功
     */
    @Override
    public void deleteById(String orderId) {
        if (DataUseUtil.isBlank(orderId)) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "未选择删除数据");
        }
        omsOrderMapper.deleteById(orderId);

    }

    @Override
    public JsonPage<OmsOrderVO> queryAllOrder(OmsOrderSearchDTO omsOrderSearchDTO) {
        Integer page = omsOrderSearchDTO.getPage();
        Integer pageSize = omsOrderSearchDTO.getPageSize();
        PageHelper.startPage(page, pageSize);
        List<OmsOrderVO> omsOrderVOS = omsOrderMapper.queryAllLimit(omsOrderSearchDTO);
        for (OmsOrderVO omsOrderVO : omsOrderVOS) {
            Integer state = omsOrderVO.getState();
            if (DataUseUtil.isNotBlank(String.valueOf(state))) {
                omsOrderVO.setStateNm(CakeStateCode.getDesc(state));
            } else {
                throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "该订单没有订单状态");
            }
            System.out.println();
        }
        return JsonPage.restPage(new PageInfo<>(omsOrderVOS));
    }

    @Override
    public List<OmsOrderVO> queryAllOrderExport() {
        List<OmsOrderVO> omsOrderVOS = omsOrderMapper.queryAllLimitExport();

        return omsOrderVOS;
    }

    @Override
    public void updateState(Integer orderId, Integer state) {
        if (DataUseUtil.isBlank(String.valueOf(state))) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "没有传递要修改的参数");
        }
        OmsOrder omsOrder = new OmsOrder();
        omsOrder.setOrderId(orderId);
        omsOrder.setUpdateTime(new Date());
        switch (state) {
            case 1:
                omsOrder.setState(CakeStateCode.DELIVE.getCode());//卖家点击后订单状态变成待收货
                omsOrderMapper.update(omsOrder);
                break;
            case 2:
                omsOrder.setState(CakeStateCode.RECEIVED.getCode());//卖家点击后订单状态变成已签收
                omsOrderMapper.update(omsOrder);
                break;
        }


    }

    @Override
    public void deleteOrderIds(List<Integer> orderIds) {
        omsOrderMapper.deleteBatch(orderIds);

    }

    @Override
    public List<OmsOrderStateVO> stateVos() {
        List<OmsOrderStateVO> orderState = new ArrayList<>();
        CakeStateCode[] values = CakeStateCode.values();
        for (CakeStateCode value : values) {
            OmsOrderStateVO vo = new OmsOrderStateVO();
            vo.setStateId(value.getCode());
            vo.setStateNm(value.getMessage());
            orderState.add(vo);
        }
        return orderState;
    }


}
